<?php


namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Storage;

/**
 * 
 * 备份数据库
 * @author litc
 */
class BackupController extends Controller{
    
    
    //备份文件列表
    public function index()
    {   
        $disk = Storage::disk('backup');
        $directory = '/'.config('app.name');
       // 获取目录下的文件
        $files = $disk->files($directory);
       // dd($files);
       // //获取目录下的所有文件(包括子目录下的文件)
       //  $allFiles = $disk->allFiles($directory);
        //dd($files);
        $dbZips = [];
        foreach ($files as $k => $v) {
            $dbZips[$k]['name'] = substr($v,strpos($v,'/')+1);
            $dbZips[$k]['path'] = $v;
            $dbZips[$k]['size'] = $this->countSize($disk->size($v));            //文件大小
            $dbZips[$k]['time'] = date('Y-m-d H:i:s', $disk->lastModified($v)); //最后修改时间
        }
        return [ 'data' => $dbZips ];
    }

   
    //删除
    public function destroy($filename)
    {
        // 取到磁盘实例
        // $filename = $request->input('filename');
        //dd($filename);
        $disk = Storage::disk('backup');
        $directory = '/'.config('app.name');
        // 删除单条文件
        $exists = $disk->exists($directory.'/'.$filename);
        if (!$exists) {
            $this->error('文件不存在');
        }

        $del = $disk->delete($directory.'/'.$filename);
        // 删除多条文件
        //$disk->delete(['test22.txt', 'icon.jpg']);
        if (!$del) {
            $this->error('删除失败');
        }
        return [ 'message' => "删除成功" ];
        
    }
   
    //备份数据库
    public function dataBackup()
    {   
        //备份数据库
        $backup = Artisan::call('backup:run', ['--only-db'=>true]);
        //$backup = Artisan::call('route:list');
        //这里注意 参数是以数组的形式
        if ($backup!=0) {
             $this->error('数据库备份失败');
        }
        return [ 'message' => "数据库备份成功" ];
    }


    //下载地址
   public function download($filename)
   {
        // $filename = $request->route('filename');
        $disk = Storage::disk('backup');
        $directory = '/'.config('app.name');
        
        $exists = $disk->exists($directory.'/'.$filename);
        if (!$exists) {
            $this->error('文件不存在');
        }
        //完整路径下载
        return response()->download(public_path().'/uploads'.$directory.'/'.$filename); 
   }

    //单位换算
    public function countSize($bit)
    {
        $type = array('Bytes','KB','MB','GB','TB');
        for($i = 0; $bit >= 1024; $i++)//单位每增大1024，则单位数组向后移动一位表示相应的单位
        {
            $bit/=1024;
        }
        return (floor($bit*100)/100).$type[$i];//floor是取整函数，为了防止出现一串的小数，这里取了两位小数
    }
   
}
